package com.fjwt.gz.mch.ctrl.realnameauth;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.third.bo.RealnameBo;
import com.fjwt.gz.core.third.interfaces.RealNameAuthInterface;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.FansAuthEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.vo.AgentAppVO;
import com.fjwt.gz.mch.ctrl.CommonCtrl;
import com.fjwt.gz.service.impl.ActivityService;
import com.fjwt.gz.service.impl.AgentAppService;
import com.fjwt.gz.service.impl.FansAuthService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.zhyx.sms.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/api/realName")
public class RealNameAuthController extends CommonCtrl {

    @Autowired
    private FansAuthService fansAuthService;
    @Value("${province.code}")
    private String provinceCode;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private AgentAppService agentAppService;

    /**
     * 实名认证接口
     **/
    @PostMapping("/atuh")
    public ApiRes realNameAuth() {
        RealnameBo realnameBo = getObject(RealnameBo.class);
        String phone = getValString("phone");
        String code = getValString("code");
        String locationAgentNo = request.getHeader("locationAgentNo");
        Long fansId = getCurrentUser().getFansId();
//        String appId = getCurrentUser().getAppId();
        String appId = request.getHeader("appid");
        log.info("实名认证接口，请求地址：/api/realName/atuh，请求参数：{}", realnameBo);
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code) || Objects.isNull(fansId)) {
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        JSONObject smsCode = SmsUtil.getSmsCOde(CS.SYS_ROLE_TYPE.MCH, phone, 10);
        if(null == smsCode){
            throw new BizException("验证码已过期！");
        }
        String smsCodeRedis = smsCode.getString("code");
        if (!smsCodeRedis.equals(code)){
            throw new BizException("验证码错误");
        }

        LambdaQueryWrapper<FansAuthEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FansAuthEntity::getFansId, fansId);
        queryWrapper.eq(FansAuthEntity::getAgentNo, locationAgentNo);
        List<FansAuthEntity> fansAuthEntityList = fansAuthService.list(queryWrapper);
        if (ObjectUtil.isNotEmpty(fansAuthEntityList)) {
            throw new BizException("该用户已实名认证");
        }

        RealNameAuthInterface realNameAuthInterface = SpringBeansUtil.getBean(provinceCode + "RealNameAuthService", RealNameAuthInterface.class);
        realnameBo.setLocationAgentNo(locationAgentNo);
        JSONObject jsonObject = realNameAuthInterface.realNameAuth(realnameBo);
        JSONObject activityJson = JSONObject.from(realnameBo);
        JSONObject data =  fansAuthService.instAuis(jsonObject, provinceCode, locationAgentNo, appId, fansId,activityJson);
        log.info("实名认证接口，请求地址：/api/realName/atuh，返回数据:{}", JSONUtil.toJsonStr(data));
        return ApiRes.ok(data);
    }

    /**
     * 转介受邀人确定进行发放待激活的卡券
     */
    @PostMapping("/confirmSendCoupon")
    public ApiRes confirmSendCoupon() {
        Long inviterId = getValLong("inviterId");
        Long fansId = getCurrentUser().getFansId();
        Long activityId = getValLong("activityId");
        Long awardId = getValLong("awardId");
        Integer awardType = getValInteger("awardType");
        String name = getValString("name");
        String telphone = getValString("telphone");
        String remark = getValString("remark");
        String agentNo = getValString("agentNo");
        String agentName = getValString("agentName");
        Long activityChannelId = getValLong("activityChannelId");
        log.info("邀请人id：{}，受邀人id：{}，活动id：{}，奖品id：{}，奖品类型：{}，姓名：{}，手机号：{}，备注：{}", inviterId, fansId, activityId, awardId, awardType, name, telphone, remark);
        if (null == inviterId || null == fansId || null == activityId || null == awardId || null == awardType || StringUtils.isEmpty(name) || StringUtils.isEmpty(telphone) || StringUtils.isEmpty(remark)) {
            return ApiRes.customFail("网络故障，请稍后重试");
        }
        ActivityEntity activityEntity = activityService.getById(activityId);
        if(null == activityEntity){
            return ApiRes.customFail("该活动不存在，请核实！");
        }
        if(4 != activityEntity.getState()){
            return ApiRes.customFail("该活动已结束，请参与最新的此类活动！");
        }
        // 不可转介本人
        if (fansId.equals(inviterId)) {
            return ApiRes.customFail("拉新邀请失败！");
        }
        // 查询该用户是否被邀请过
        List<FansAwardEntity> entityList = fansAwardService.fansActiveCouponBefore(fansId);
        if(!entityList.isEmpty()){
            throw new BizException("您已被邀请，请勿重复");
        }
        log.info("转介新人邀约记录：邀约人id：{}，奖品id：{}，奖品类型：{}，奖品备注：{}", inviterId, awardId, awardType, remark);
        List<FansAwardEntity> list = fansAwardService.selectListFansAward(inviterId, awardId, awardType, remark, "2");
        if (null != list && !list.isEmpty()) {
            for (FansAwardEntity f : list) {
                JSONObject json = JSONObject.parseObject(f.getExtraJson());
                if (fansId.equals(json.getLong("fansId"))) {
                    return ApiRes.customFail("已确认拉新邀请，请勿重复确认！");
                }
            }
        }

        AgentAppVO agentApp = agentAppService.getAgentApp(activityId);
        FansAuthEntity fansAuthEntity = fansAuthService.getOne(FansAuthEntity.gw().eq(FansAuthEntity::getAgentNo, agentApp.getAgentNo()).eq(FansAuthEntity::getFansId, fansId));
        JSONObject json = new JSONObject();
        json.put("fansId", fansId);
        json.put("name", name);
        json.put("telphone", telphone);
        json.put("agentNo", agentNo);
        json.put("agentName", agentName);
        json.put("date",new Date());
        json.put("templateNo", activityEntity.getActivityTemplateNo());
        FansAwardEntity fansAwardEntity = new FansAwardEntity();
        fansAwardEntity.setAppId(agentApp.getAppId());
        fansAwardEntity.setAwardId(awardId);
        fansAwardEntity.setAwardType(awardType);
        fansAwardEntity.setFansId(inviterId);
        fansAwardEntity.setRemark(remark);
        fansAwardEntity.setCreatedAt(new Date());
        if (ObjectUtils.isNotEmpty(fansAuthEntity) && ObjectUtils.isNotEmpty(fansAuthEntity.getCstmNo())) {
            json.put("failDetail", "对方属于老用户");
            fansAwardEntity.setState(Constants.FANS_AWARD_STATE.DISABLED);
        } else {
            fansAwardEntity.setState(Constants.FANS_AWARD_STATE.ACTIVATE);
        }
        fansAwardEntity.setExtraJson(json.toJSONString());

        fansAwardEntity.setOverTime(activityEntity.getEndTime());
        fansAwardEntity.setActivityChannelId(activityChannelId);
        fansAwardService.getBaseMapper().insert(fansAwardEntity);
        FansAwardEntity dto = new FansAwardEntity();
        BeanUtils.copyProperties(fansAwardEntity,dto);
        return ApiRes.ok(dto);
    }
}
